class MonitoringsController < ApplicationController
  
  require 'socket'
  require 'ping'
  #before_filter :ping_machine
  before_filter :ensure_login
  
  def index
  #  @machines = Machine.find_by_sql("SELECT m.id as id,m.machine_name as machine_name,m.ip_adr as ip_adr,m.state as state,m.mode as mode,i.created_at as created_at FROM machines m, incidents i WHERE m.id=i.machine_id ORDER BY i.created_at DESC LIMIT 0,1")
     @warning = Machine.find_by_sql("SELECT count(id) as nb from incidents where date(created_at) = date(now())")
     @up = Machine.find_by_sql("SELECT count(id) as nb from machines where state='connecté'")
     @down = Machine.find_by_sql("SELECT count(id) as nb from machines where state='déconnecté'")
     @machines = Machine.all 
     @incidents = Incident.find(:all, :order => "created_at DESC", :limit => 10, :include => :machine, :conditions => "machine_id in (SELECT id from machines) AND resolution_date IS NULL")

  end
  
  
  def ping_machine

    @tab_ip = Machine.find(:all, :select => "ip_adr, id")
    @tab_ip.each do |ip|
      
     if Ping.pingecho(ip.ip_adr, 5, "echo") 
          Machine.update_all("state_number = 1", [ "id = ?", ip.id ])
          Machine.update_all("state = 'connecté'", [ "id = ?", ip.id ])
          Incident.update_all({:resolution_date => Time.now}, "resolution_date IS NULL AND machine_id = #{ip.id}")
          Incident.update_all({:updated_at => Time.now}, "resolution_date IS NULL AND machine_id = #{ip.id}")

      else
          Machine.update_all("state_number = 0", [ "id = ?", ip.id ])
          Machine.update_all("state = 'déconnecté'", [ "id = ?", ip.id ])
          Incident.create(:machine_id => ip.id,
            :incident_type => 'Host unreachable',
            :created_at => Time.now,
            :updated_at => Time.now)
       end

      end
      respond_to do |format|
      format.html { redirect_to(views_url) }
      format.xml {head :ok}
      end
  end 



  
  def ping_machine_manuel
    #que faire
   @ip = Machine.find(params[:id])
   if Ping.pingecho(@ip.ip_adr, 5, "echo")
          Machine.update_all("state_number = 1", [ "id = ?", @ip.id ])
          Machine.update_all("state = 'connecté'", [ "id = ?", @ip.id ])
          Incident.update_all({:resolution_date => Time.now}, "resolution_date IS NULL AND machine_id = #{@ip.id}")
          Incident.update_all({:updated_at => Time.now}, "resolution_date IS NULL AND machine_id = #{@ip.id}")
          valeur = "Ping OK"
      else
          Machine.update_all("state_number = 0", [ "id = ?", @ip.id ])
          Machine.update_all("state = 'déconnecté'", [ "id = ?", @ip.id ])
          Incident.create(:machine_id => @ip.id,
            :incident_type => 'Host unreachable',
            :created_at => Time.now,
            :updated_at => Time.now)
          valeur = "Ping NON OK"
       end
    flash[:notice] = valeur
   redirect_to :controller => "views", :action => "index"
  end

  
end